<?php

class Error extends Exception {

	public function __construct($message = "", $code = NULL) {
		parent::__construct($message, $code);
	}

	public static function exception(Exception $e) {
		self::saveError($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTrace(), $e->getTraceAsString());
		$content = self::render();

		$tpl = new Templater(RP . "tpl/admin/");
		$tpl->assign('content', $content);
		echo $tpl->fetch('error.html');
	}

	public static function error($no, $str, $file, $line) {
		self::saveError($no, $str, $file, $line);
	}

	private static $_errors;

	public static function saveError($no, $message, $file, $line, $trace = array(), $traceAsString = "") {
		$file_content = self::file($file, $line);

		$_trace = array();
		foreach ($trace as $k => $t) {
			$_trace[$k]['file'] = pathinfo($t['file'], PATHINFO_BASENAME);
			$_trace[$k]['file_content'] = self::file($t['file'], $t['line']);
			$_trace[$k]['funtion'] = "{$t['class']}::{$t['function']}()";
		}

		self::$_errors[] = array(
			'code' => $no,
			'message' => $message,
			'file' => pathinfo($file, PATHINFO_BASENAME),
			'file_content' => $file_content,
			'line' => $line,
			'trace' => $_trace,
			'traceAsString' => $traceAsString
		);
	}

	private static function file($file, $line) {
		$line--;
		$file_content = "<ol start=\"$line\">";
		$_file = file($file);
		
		//$_file[$line] = "<span class=\"current\">{$_file[$line]}</span>";
		
		/*$text = implode("\r\n", array_slice($_file, $line-5, $line+5));
		$text = highlight_string("<?php\r\n".$text."\r\n?>", true);
		$lines = preg_split("~\r\n|\r|\n~", $text);
		array_pop($lines);
		array_shift($lines);*/
		//$file_content = implode("<br/>", array_slice($_file, $line-5, $line+5));
		
		$start = $line - 5 >= 0 ? $line-5 : 0;
		$finish = $line + 5 > count($_file) ? count($_file) : $line + 5;
		
		for ($i = $start; $i < $finish; $i++) {
			$file_content .= "<li><code style=\"white-space: pre;\">";
			if ($i == $line) $file_content .="<span class=\"current\">";
			$file_content .= htmlspecialchars($_file[$i]);
			if ($i == $line) $file_content .="</span>";
			$file_content .= "</code></li>";
		}
		
		$file_content .= "</ol>";

		return $file_content;
	}

	public static function getErrors() {
		return self::$_errors;
	}

	public static function render() {
		$tpl = new Templater(RP . "tpl/admin/");
		$tpl->assign('errors', self::$_errors);
		return $tpl->fetch('_error.html');
	}

}